var router = require('libs/router').router;
var pages = require('libs/pages');
var ItemMixin = require('mixins/item');
var libs = require('libs/libs');
var api = libs.api;
var valide = libs.formValide;

var _page = {
    addressId: false,
    back: false
}

var _location = false;

var _address_new = false;
var _address_count = 0;

var _user = SA.get('USER')

SA.set('Uuinfo', {})
// var uuinfo;

function checkName(stat, reg){
    if (!stat && reg.event){
        reg.tips('用户名不正确');
        return false;
    }
    else {
        // if (libs.strLen(this.value)>2&&libs.strLen(this.value)<20){
        if (this.value.length>=2&&this.value.length<20){
            return true;
        }
        else {
            reg.tips('用户名长度必须大于2小于20')
            return false;
        }
    }
}
function checkAddress(stat, reg){
    if (!stat && reg.event){
        reg.tips('请正确输入地址')
        return false;
    }
    else {
        if (stat){
            if (this.value.length>5){
                if (this.value.length<50){
                    return true;
                }
                else{
                    reg.tips('最多不能超过50个字')
                }
            }
            else {
                reg.tips('地址长度必须大于5')
                return false;
            }
        }
        return stat;
    }
}

function checkMobile(stat, reg){
    if (!stat && reg.event){
        reg.tips('请输入正确的手机号码')
    }
    return stat
}

//后退处理
function backback(){
    // 直接返回服务页
    var _back = _page.back;
    sessionStorage.removeItem('_tmp_new_address')
    if (_back){
        router(_back)
    }
    else {
        router.goback()
    }
}

var bindEvent = function(){
    var submit_stat = true;

    var check_uc_edit = valide('Form_uc_edit_user_info')
    ('address_edit_name', 'username', checkName)
    ('address_edit_mobile', 'mobile', checkMobile)
    ('address_edit_zone', 'noop')
    ("address_edit_address", 'username', checkAddress)

    $('#address_edit_zone_li').click(function(){
        if (_address_new){
            var tmp_address = {
                address_edit_name: $('#address_edit_name').val(),
                address_edit_mobile: $('#address_edit_mobile').val(),
                address_edit_address: $('#address_edit_address').val()
            }
            sessionStorage.setItem('_tmp_new_address', JSON.stringify(tmp_address))
        }
        router('uc/location', {back:'uc/addressedit'})
    })

    // $('.uc_address_edit_submit').off('click')
    // $('.uc_address_edit_submit').css('backgroundColor', '#ccc')

    // 必须写在校验(check_uc_edit)之后，不然会被冲掉
    $('#address_edit_name, #address_edit_mobile, #address_edit_address').on('input',function(){
        _valide()
    })

    var _post_query;
    function _valide(){
        check_uc_edit(function(query, eles){
            // console.log(query);
            var _uuinfo = SA.get('Uuinfo')
            if (query.ckstat){
                _post_query = false;
                $('.uc_address_edit_submit').one('click', function(){ _submit_adress_edit() })
                $('.uc_address_edit_submit').removeAttr('style')

                query.method = 'get'
                query.districtName = _user.info.currentCommunity.communityName
                query.communityId = _location ? _location.communityId : _user.info.currentCommunity.communityId
                query.dscd = _location ? _location.dscd : _user.info.currentCommunity.districtId
                query.address = query.address_edit_address
                query.contact = query.address_edit_name
                query.contactPhone = query.address_edit_mobile
                query.login = _user.login

                delete query.ckstat
                delete query.address_edit_address
                delete query.address_edit_name
                delete query.address_edit_zone
                delete query.address_edit_mobile

                var postdata = {
                    login: _user.login,
                    userName: query.contact,
                    method: 'get'
                }
                if (_page.addressId){
                    query.id = _page.addressId
                }
                if (_uuinfo.isDefaultAdd){
                    query.isDefaultAdd = _uuinfo.isDefaultAdd?1:0
                }
                _post_query = query
            }
            else{
                $('.uc_address_edit_submit').off('click')
                $('.uc_address_edit_submit').css('backgroundColor','#ccc')
            }
        })
    }
    _valide()

    function _submit_adress_edit(){
        var pd = _post_query
        if (!pd) return;
        if (submit_stat){
            submit_stat = false;
            api.req('/createUserAddress', pd, function(data, status, xhr){
                if (!data.code){
                    backback()
                }
            })
        }
    }



}

function renderHtml(){
    // console.log(this);
    var me = this;
    var oUser = SA.get('USER');
    var _uuinfo = SA.get('Uuinfo')
    // if (_uuinfo.address_edit_name){
    //     // React.unmountComponentAtNode(document.getElementById(me.name))
    //     me.main()
    // }
    // else{
    //     api.req('/userInfo', {login: oUser.login, method: 'get'}, function(ddd){
    //         var _resault = {login: oUser.login, info: ddd}
    //         SA.set('USER', _resault)
    //         _user = _resault;
    //         var uuinfo = {
    //             address_edit_name: _user.info.userName,
    //             address_edit_mobile: _user.info.mobile,
    //             address_edit_address: _user.info.address.address||_user.info.address||'',
    //             address_edit_zone: (_user.info.currentCommunity.cityName + _user.info.currentCommunity.districtName + _user.info.currentCommunity.communityName||'')
    //         }
    //         SA.set('Uuinfo', uuinfo)
    //         // React.unmountComponentAtNode(document.getElementById(me.name))
    //         me.main()
    //     })
    // }

    api.req('/userInfo', {login: oUser.login, method: 'get'}, function(ddd){
        var _resault = {login: oUser.login, info: ddd}
        SA.set('USER', _resault)
        _user = _resault;
        var _tna = sessionStorage.getItem('_tmp_new_address');
        _tna = JSON.parse(_tna)
        var uuinfo = {
            address_edit_name: _tna?_tna.address_edit_name:'',
            address_edit_mobile: _tna?_tna.address_edit_mobile: (_address_count ? '': _user.info.mobile),
            address_edit_address: _tna?_tna.address_edit_address:'',
            address_edit_zone: (function(){
                /*
                 {
                    "cityId":"440100",
                    "cityName": "北京市"
                    "_location":true,
                    "communityId":"3dba18f00b36435599e4c2cb00587167",
                    "communityName":"君华香柏",
                    "dscd":"440111"
                }
                */
                if (_location){
                    return _location.cityName + _location.districtName + _location.communityName || ""
                }
                return (_user.info.currentCommunity.cityName + _user.info.currentCommunity.districtName + _user.info.currentCommunity.communityName||'')
            })()
        }
        if (_uuinfo.addressId){
            uuinfo = _uuinfo;
            uuinfo.address_edit_zone = (function(){
                if (_location){
                    return _location.cityName + _location.districtName + _location.communityName || ""
                }
                return (_user.info.currentCommunity.cityName + _user.info.currentCommunity.districtName + _user.info.currentCommunity.communityName||'')
            })()
            SA.set('Uuinfo', uuinfo)
            me.main()
        }
        else{
            SA.set('Uuinfo', uuinfo)
            me.main()
        }
    })

}

//演示模块
var Show = React.createClass({
    mixins: [ItemMixin],
    componentWillMount: function() {
        if (this.props.data){
            this.setState({
                user: this.props.data
            })
        }
    },
    render:function(){
        var uuu = this.state.user
        // var fulladd = uuu.address_edit_address.cityName + uuu.address_edit_address.districtName + uuu.address_edit_address.communityName || ''
        var fulladd = uuu.address_edit_address||''
        return (
            <div className="default_div app_index">
                <ul className="default_Picture">
                    <li>
                        <label>姓名</label>
                        <input id="address_edit_name" type="text" defaultValue={uuu.address_edit_name} placeholder="请输入姓名"/>
                        {/*<i className="iconfont icon-xiangyou"></i>*/}
                    </li>
                    <li>
                        <label>手机号</label>
                        <input id="address_edit_mobile" type="text" defaultValue={uuu.address_edit_mobile} placeholder="请输入手机号"/>
                        {/*<i className="iconfont icon-xiangyou"></i>*/}
                    </li>
                    <li id="address_edit_zone_li">
                        <label>所在小区</label>
                        <input id="address_edit_zone" type="text" defaultValue={uuu.address_edit_zone} readOnly="readOnly"/>
                        <i className="iconfont icon-xiangyou"></i>
                    </li>
                    <li>
                        <label>详细地址</label>
                        <input id="address_edit_address" type="text" defaultValue={fulladd} placeholder="请输入具体到门牌号的地址"/>
                        {/*<i className="iconfont icon-xiangyou"></i>*/}
                    </li>
                </ul>
                <div className="default_foot" style={{backgroundColor:'transparent',marginBottom:"0.2rem"}}>
                    <div className="f_submit" style={{width:'100%'}}>
                        <input type="submit" defaultValue="确定" className="f_btn uc_address_edit_submit" />
                    </div>
                </div>
                {/*<div className="default_foot default_foot_btn3 defalut_color">
                    <a href="javascript:;">确定</a>
                </div>*/}
            </div>
        );
    }
});

function start(name){
    return pages.new({
        boot:function(){
            this.name = name;
        },
        trigger:function(self, data){
            if (data._location){
                _location = data;
                // console.log('========= location');
                // console.log(_location);
            }

            if (data && data.address_edit_name){
                _address_new = false;
                this.libs.changeTitle('编辑地址');    //更改当前页面标题
                SA.set('Uuinfo', data)
                this.main()
            }
            else{
                _address_new = true;
                if (data.count || data.count===0){
                    _address_count = data.count
                }
                this.libs.changeTitle('新增地址');    //更改当前页面标题
                renderHtml.call(this)

            }
        },
        main: function(){
            var _uuinfo = SA.get('Uuinfo')
            if (_uuinfo.back){
                _page.back = _uuinfo.back
            }
            if (_uuinfo.addressId){
                _page.addressId = _uuinfo.addressId
            }
            this.render(
                <Show itemDefaultMethod={bindEvent} data={_uuinfo}/>,
                document.getElementById(name)
            )
        },
        end: function(){
            var _go = router.pre()
            function _end_clear(){
                _page = {
                    addressId: false,
                    back: false
                }
                SA.deleter('Uuinfo');
            }

            if (_go&&_go.hash!=='uc/addressedit'){
                _end_clear()
            }

            if (!_go){
                _end_clear()
            }

            _location = false

            React.unmountComponentAtNode(document.getElementById(this.name))
        }
    })
}

module.exports = start;
